from typing import NamedTuple

from opentelemetry.exporter.prometheus_remote_write import PrometheusRemoteWriteMetricsExporter, TimeSeries

PROMETHEUS_REMOTE_WRITE_URL = "https://cprom.bj.baidubce.com/insert/prometheus/api/v1/write"
AUTHORIZATION_HEADERS = {
    "Authorization": "Bearer jwt",
    "InstanceId": "cprom-instanceId",
    "cprom-v65bnegx755z1": "application/x-protobuf",
    "Content-Encoding": "snappy"
}

exporter: PrometheusRemoteWriteMetricsExporter = PrometheusRemoteWriteMetricsExporter(
    endpoint=PROMETHEUS_REMOTE_WRITE_URL,
    headers=AUTHORIZATION_HEADERS,
)

class Label(NamedTuple):
    broadband_number: str
    vlan_id: str
    network_type: str
    network_interface: str
    account_number: str
    device_number: str
    province: str
    telecom_carriers: str
    device_model: str
    device_group: str
    business_type: str


class NetworkStatus:
    def __init__(self, uplink_bandwidth_usage: int, downlink_bandwidth_usage: int, network_received_total: int,
                 network_transmitted_total: int, timestamp: int):
        self.timestamp = timestamp
        self.uplink_bandwidth_usage: int = uplink_bandwidth_usage
        self.downlink_bandwidth_usage: int = downlink_bandwidth_usage
        self.network_received_total: int = network_received_total
        self.network_transmitted_total: int = network_transmitted_total


def _create_gauge(name: str, value: int, timestamp: int, labels: dict):
    timeseries = []
    ts = TimeSeries()
    ts.labels.append(exporter._label("__name__", name))
    for label_name, label_value in sorted(labels.items(), key=lambda x: x[0]):
        ts.labels.append(exporter._label(label_name, str(label_value)))
    ts.samples.append(exporter._sample(value, timestamp))
    timeseries.append(ts)
    message = exporter._build_message(timeseries)
    exporter._send_message(message, exporter._build_headers())


def report_device_network_status_to_prometheus(network_status: NetworkStatus, labels: Label):
    _create_gauge("uplink_bandwidth_usage_bytes", network_status.uplink_bandwidth_usage, network_status.timestamp, labels._asdict())
    _create_gauge("downlink_bandwidth_usage_bytes", network_status.downlink_bandwidth_usage, network_status.timestamp, labels._asdict())
    _create_gauge("network_bytes_received_total", network_status.network_received_total, network_status.timestamp, labels._asdict())
    _create_gauge("network_bytes_transmitted_total", network_status.network_transmitted_total, network_status.timestamp, labels._asdict())
